from django.shortcuts import render
from django.views import View
from django import http
from django_redis import get_redis_connection
import re
import logging
import json
import random

from IHome.utils.errmsg_info import error_no, error_msg
from IHome.libs.captcha.captcha import captcha
from IHome.libs.yuntongxun.ccp_sms import CCP
from celery_tasks.sms.tasks import send_sms_code

# Create your views here.
# 创建日志生成器
logger = logging.getLogger('django')


class SMSCodeView(View):
    def post(self, request):
        # 提取参数
        json_dict = json.loads(request.body.decode())
        mobile = json_dict.get('mobile')
        uuid = json_dict.get('id')
        text_client = json_dict.get('text')

        conn = get_redis_connection('verify_code')
        flag = conn.get('flag_%s' % mobile)

        if flag:
           return http.JsonResponse({'errno': error_no['REQERR'], 'errmsg': error_msg['REQERR']})

        # 校验参数
        if not all([mobile, uuid, text_client]):
            return http.JsonResponse({'errno': error_no['PARAMERR'], 'errmsg': error_msg['PARAMERR']})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'errno': error_no['DATAERR'], 'errmsg': error_msg['DATAERR']})
        if not re.match(r'^[\w-]+$', uuid):
            return http.JsonResponse({'errno': error_no['DATAERR'], 'errmsg': error_msg['DATAERR']})

        text_server = conn.get('img_%s' % uuid)
        if not text_server:
            return http.JsonResponse({'errno': error_no['NOTDATA'], 'errmsg': error_msg['NOTDATA']})
        if text_client.lower() != text_server.lower().decode():
            return http.JsonResponse({'errno': error_no['DATAERR'], 'errmsg': error_msg['DATAERR']})

        # 删除图形验证码
        conn.delete('img_%s' % uuid)

        # 随机生成六位数字
        sms_code = '%06d' % random.randint(0, 999999)
        print(sms_code)

        # 创建管道
        pl = conn.pipeline()

        # 保存短信验证码
        pl.setex('sms_%s' % mobile, 300, sms_code)
        pl.setex('flag_%s' % mobile, 60, 1)
        # 执行管道
        pl.execute()

        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        # 异步方案
        send_sms_code.delay(mobile, sms_code)

        return http.JsonResponse({'errno': error_no['OK'], 'errmsg': error_msg['OK']})


class ImageCodeView(View):
    def get(self, request):
        cur_uuid = request.GET.get('cur')
        pre_uuid = request.GET.get('pre')

        if not cur_uuid:
            return http.HttpResponse('无数据')

        if not re.match(r'^[\w-]+$', cur_uuid):
            return http.HttpResponse('cur_uuid格式错误')

        if pre_uuid:
            if not re.match(r'^[\w-]+$', pre_uuid):
                return http.HttpResponse('pre_uuid格式错误')

        text, image = captcha.generate_captcha()
        print(text)
        try:
            conn = get_redis_connection('verify_code')
            conn.setex('img_%s' % cur_uuid, 300, text)
        except Exception as e:
            logger.error(e)
            return http.HttpResponse('访问数据库失败')

        return http.HttpResponse(content=image, content_type='image/jpg')


